﻿package kliment.utils 
{
	import flash.display.DisplayObjectContainer;
	import flash.events.KeyboardEvent;
	
	/**
	 * ...
	 * @author Kliment
	 */
	public class KeyboardChecker 
	{
		private var _target:DisplayObjectContainer;
		private var _keysCollection:Array = [];
		
		public function KeyboardChecker(target:DisplayObjectContainer) 
		{
			_target = target;
			
			_target.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler);
			_target.addEventListener(KeyboardEvent.KEY_UP, keyboardHandler);
		}
		
		public function keyIsDown(keyCode:uint):Boolean
		{
			return (_keysCollection.indexOf(keyCode) > -1);
		}
		
		public function dispouse():void
		{
			_keysCollection = [];
			
			_target.removeEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler);
			_target.removeEventListener(KeyboardEvent.KEY_UP, keyboardHandler);
			_target = null;
		}
		
		private function keyboardHandler(event:KeyboardEvent):void
		{
			switch (event.type)
			{
				case KeyboardEvent.KEY_DOWN:
					keyHandler(event.keyCode, true);
				break;
				
				case KeyboardEvent.KEY_UP:
					keyHandler(event.keyCode, false);
				break;
			}
		}
		
		private function keyHandler(keyCode:uint, status:Boolean):void
		{
			var index:int = _keysCollection.indexOf(keyCode);
			if (status && index < 0)
			{
				_keysCollection.push(keyCode);
			}
			else if (!status)
			{
				_keysCollection.splice(index, 1);
			}
		}
	}

}